﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Runtime.InteropServices;
using Slja.SMS;
using System.Text;
using System.Configuration;
using System.Globalization;
using Slja.GSMUtility;
using log4net;

namespace SljaSMS
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class Sms : System.Web.Services.WebService
    {
        //静态变量       
        //private static Slja.GSMMODEM.GSMModem _gsm;
      
        static Sms()
        {
            //string strAutoRecvFlag = ConfigurationManager.AppSettings["SmsAutoRecive2DB"];
            //if (strAutoRecvFlag.ToUpper()=="TRUE")
            //{
            //    //绑定：自动接收,执行"阅读"动作的事件
            //    GSM.OnRecieved += new Slja.GSMMODEM.GSMModem.OnRecievedHandler(GSMOnRecieved);
            //    //设置：自动删除
            //    GSM.AutoDelMsg = true;
            //}
        }

        static void GSMOnRecieved(object sender, EventArgs e)
        {
            Slja.GSMMODEM.GSMModem curGSM = (Slja.GSMMODEM.GSMModem)sender;
            int newMsgIdx = curGSM.newMsgIndex;
            string strMsg = curGSM.ReadMsgByIndex(newMsgIdx);
            string[] arr =  new string[] { strMsg };
            List<SmsMsgInfo> msgList = SmsUti.ConvertRecivedMsgFormat(arr);
            //生成Model数据库列表
            List<Slja.GSMUtility.Model.sms_MsgRecive> listModel = SmsUti.AssignReciveModelList(msgList);
            //保存数据库
            Slja.GSMUtility.DAL.sms_MsgRecive dal = new Slja.GSMUtility.DAL.sms_MsgRecive();
            List<int> listid = dal.Add(listModel);
        }

        [WebMethod]
        public List<Slja.GSMUtility.Model.sms_MsgSend> Send(List<string> sms_Reciver, string Msg, int SendUser)
        {
            //记录日志
            ILog logger = LogManager.GetLogger("File");
            logger.Info(DateTime.Now.ToString("HH:mm:ss fff")+"\t");

            //int n = 0;
            //uint[] ArrStatus = new uint[sms_Reciver.Count];
            ////逐个号码发送一遍；若失败，会再发送，但每个号码最多再重复发送3次
            //while (Array.Exists<uint>(ArrStatus,delegate(uint nState){return nState==0;})
            //    && n++ < 3)
            //{
            //    for (int i = 0; i < sms_Reciver.Count; i++)
            //    {
            //        if (ArrStatus[i] == 0)
            //        {
            //            logger.Info(DateTime.Now.ToString("HH:mm:ss fff") + "\t");
            //            ArrStatus[i] = GSM.SendMsg(sms_Reciver[i], Msg);
            //            logger.Info(DateTime.Now.ToString("HH:mm:ss fff") + "\t");
            //        }
            //    }
            //}
            //logger.Info(DateTime.Now.ToString("HH:mm:ss fff") + "\t");
            //记入日志
            List<Slja.GSMUtility.Model.sms_MsgSend> modellist = new List<Slja.GSMUtility.Model.sms_MsgSend>();
            try
            {
                for (int k = 0; k < sms_Reciver.Count; k++)
                {
                    Slja.GSMUtility.Model.sms_MsgSend send = new Slja.GSMUtility.Model.sms_MsgSend();
                    send.MsgContent = Msg;
                    send.RecvNO = sms_Reciver[k];
                    send.SendStatus = 0;
                    send.SendTime = DateTime.Now;
                    send.SendUser = SendUser;
                    modellist.Add(send);
                }
                Slja.GSMUtility.DAL.sms_MsgSend dal = new Slja.GSMUtility.DAL.sms_MsgSend();
                dal.Add(modellist);
              
            }
            catch (Exception err)
            {
                logger.Error(err.Message + err.StackTrace);
            }
            return modellist;//将短信返回（包含Id列）
        }
        [WebMethod]
        public List<Slja.GSMUtility.Model.sms_MsgRecive> ReciveNewMsg()
        {
            //收记录
            //string[] arrUnRead = GSM.GetUnreadMsg();
           // List<SmsMsgInfo> msgList = SmsUti.ConvertRecivedMsgFormat(arrUnRead);
            //生成Model数据库列表
            //List<Slja.GSMUtility.Model.sms_MsgRecive> listModel = SmsUti.AssignReciveModelList(msgList);
            //保存数据库
           // Slja.GSMUtility.DAL.sms_MsgRecive dal = new Slja.GSMUtility.DAL.sms_MsgRecive();
           // List<int> listid = dal.Add(listModel);
           
            //删除短信猫上的已收短信；并给收到的短信model的ID字段赋值，以便返回
            //for (int k = 0; k < msgList.Count; k++)
            //{
            //    //SmsDLL.Delete(msgList[k].Index.ToString());
            //    GSM.DelMsgByIndex(msgList[k].Index);
            //    listModel[k].ID = listid[k];
            //}
            //return listModel;
            Slja.GSMUtility.DAL.sms_MsgRecive recv = new Slja.GSMUtility.DAL.sms_MsgRecive();
            return recv.GetNewMsg();
        }
         [WebMethod]
        public int MsgRead(int recvmsgModelID,string UserName)
        {
            Slja.GSMUtility.DAL.sms_MsgRecive dal = new Slja.GSMUtility.DAL.sms_MsgRecive();
            return dal.Read(recvmsgModelID, UserName);
        }
         [WebMethod]
         public List<MsgStatus> GetMsgSendStatus(int[] MsgIDs)
         {
             Slja.GSMUtility.DAL.sms_MsgSend dal = new Slja.GSMUtility.DAL.sms_MsgSend();
             List<MsgStatus> list = dal.GetMsgSendStatus(MsgIDs);
             //List<KeyValuePair<int, byte>> MsgStatus = new List<KeyValuePair<int, byte>>();
             //for (int i = 0; i < list.Count; i++)
             //{
             //    MsgStatus.Add(new KeyValuePair<int, byte>(list[i].MsgID, list[i].Status));
             //}             
             return list;
         }
    }


}